package com.jc.service.supplier_product;

import com.jc.cds.model.CustomSupplierProduct;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.base.service.BaseServiceImpl;
import com.jc.ds.mapper.BaseCustomMapper;
import com.jc.ds.model.*;
import com.jc.framework.enums.ImageStatus;
import com.jc.framework.enums.ProductPrice;
import com.jc.framework.enums.Push;
import com.jc.framework.util.SpringUtils;
import com.jc.service.api.product.Attr;
import com.jc.service.api.product.Image;
import com.jc.service.api.product.Product;
import com.jc.service.api.product.Sku;
import com.jc.service.attribute.AttributeService;
import com.jc.service.attributevalue.AttributeValueService;
import com.jc.service.productattribute.ProductAttributeService;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@SuppressWarnings("all")
@Service
public class SupplierProductServiceImpl extends BaseServiceImpl<SupplierProduct, CustomSupplierProduct, Long> implements SupplierProductService {
	@Override
	public BaseCustomMapper<CustomSupplierProduct, Long> getCustomMapper() {
		return null;
	}

	public Logger getLoger() {
		return LoggerFactory.getLogger(this.getClass());
	}
	@Autowired
	SupplierGoodsService supplierGoodsService;
	@Autowired
	AttributeService attributeService;
	@Autowired
	AttributeValueService attributeValueService;
	@Autowired
	ProductAttributeService productAttributeService;
	@Autowired
	SupplierProductPriceService supplierProductPriceService;
	@Autowired
	SupplierGoodsPictureListService supplierGoodsPictureListService;

	@Override
	@Transactional
	public void pullPro(Product product){
		try{
			//必填参数校验
			isProNull(product);
			//封装对象
			SupplierGoods supplierGoods = packageObjectGoods(product);
			getLoger().debug("======封装supplierGoods对象 "+ supplierGoods);
			//保存 supplierGoods
			SupplierGoods supplierGoodsQu = new SupplierGoods();
			List<SupplierGoods> supplierGoods1 = supplierGoodsService.queryAll(supplierGoodsQu);
			supplierGoodsService.add(supplierGoods,false);
			//保存详情图片
			List<Image> detailImages = product.getDetailImages();
			detailImages.forEach(detailImage->{
				SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
				supplierGoodsPictureList.setGid(supplierGoods.getId());
				supplierGoodsPictureList.setGoodsId(String.valueOf(supplierGoods.getSupplierId()));
				supplierGoodsPictureList.setImageType(2);
				List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(supplierGoodsPictureList);
				if (CollectionUtils.isNotEmpty(supplierGoodsPictureLists)){
					return;
				}
				supplierGoodsPictureList.setImagePath(detailImage.getImageUrl());
				supplierGoodsPictureList.setWidth(detailImage.getWidth());
				supplierGoodsPictureList.setHeight(detailImage.getHeight());
				supplierGoodsPictureList.setImageOrder(detailImage.getSort());
				supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
			});

			List<Image> rotationImages = product.getRotationImages();
			rotationImages.forEach(rotationImage->{
				SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
				supplierGoodsPictureList.setGid(supplierGoods.getId());
				supplierGoodsPictureList.setGoodsId(String.valueOf(supplierGoods.getSupplierId()));
				supplierGoodsPictureList.setImageType(1);
				List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(supplierGoodsPictureList);
				if (CollectionUtils.isNotEmpty(supplierGoodsPictureLists)){
					return;
				}
				supplierGoodsPictureList.setImagePath(rotationImage.getImageUrl());
				supplierGoodsPictureList.setWidth(rotationImage.getWidth());
				supplierGoodsPictureList.setHeight(rotationImage.getHeight());
				supplierGoodsPictureList.setImageOrder(0);
				supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
			});
			//保存对应的属性
			List<Attr> attrs = product.getAttrs();
			attrs.forEach(attr -> {
				//保存属性
				Attribute attribute = new Attribute();
				attribute.setProductAttributeName(attr.getAttrName());
				attribute.setIsValid(1);
				List<Attribute> attributes = attributeService.queryAll(attribute);
				if (attributes != null && attributes.size() > 0){
					return;
				}
				attribute.setCreateTime(new Date());
				attributeService.add(attribute,false);
				Set<String> attrValues = attr.getAttrValues();
				attrValues.forEach(attrValue->{
					//保存属性值
					AttributeValue attributeValue = new AttributeValue();
					attributeValue.setAttributeNameId(Long.valueOf(attribute.getId()));
					attributeValue.setAttributeName(attribute.getProductAttributeName());
					attributeValue.setAttributeValue(attrValue);
					List<AttributeValue> attributeValues = attributeValueService.queryAll(attributeValue);
					if(attributeValues != null && attributeValues.size() > 0){
						return;
					}
					attributeValueService.add(attributeValue,false);
				});
			});
			//保存sku
			List<Sku> skus = product.getSkus();
			skus.forEach(sku -> {
				SupplierProduct supplierProduct = new SupplierProduct();
				supplierProduct.setGid(supplierGoods.getId());
				supplierProduct.setProductId(String.valueOf(sku.getProductId()));
				List<SupplierProduct> supplierProducts = this.queryAll(supplierProduct);
				if (supplierProducts != null && supplierProducts.size() > 0){
					return;
				}
				supplierProduct = packageObjectProduct(sku, supplierGoods.getId());
				this.add(supplierProduct,false);
				List<Map<String, Object>> attrlist = sku.getAttrlist();
				SupplierProduct finalSupplierProduct = supplierProduct;
				attrlist.forEach(attrSku->{
					for(String key : attrSku.keySet()){
						String value = String.valueOf(attrSku.get(key));
						//根据 key 查询属性id
						Attribute skuAttr = new Attribute();
						skuAttr.setProductAttributeName(key);
						List<Attribute> attributes = attributeService.queryAll(skuAttr);
//						List<Attribute> attributes = new ArrayList<>();
//						Attribute attribute = new Attribute();
//						attribute.setId(1);
//						attribute.setProductAttributeName("规格");
//						attributes.add(attribute);
						if (attributes != null && attributes.size() > 0){
							//查询属性值是否存在 不存在新增
							AttributeValue attributeValue = new AttributeValue();
							attributeValue.setAttributeValue(value);
							attributeValue.setAttributeNameId(Long.valueOf(attributes.get(0).getId()));
							List<AttributeValue> attributeValues = attributeValueService.queryAll(attributeValue);
							if (CollectionUtils.isEmpty(attributeValues)){
								//不存在 新增
								attributeValue.setAttributeName(key);
								attributeValueService.add(attributeValue,false);
							}
							//保存sku 和attr的关联表
							ProductAttribute productAttribute = new ProductAttribute();
							//skuId
							productAttribute.setProductId(finalSupplierProduct.getId());
							//属性名称id
							productAttribute.setAttributeId(attributes.get(0).getId());
							//属性名称name
							productAttribute.setAttributeName(attributes.get(0).getProductAttributeName());
							//属性值
							productAttribute.setAttributeValue(attributeValue.getAttributeValue());
							List<ProductAttribute> productAttributes = productAttributeService.queryAll(productAttribute);
							//存在直接return;
							if (CollectionUtils.isNotEmpty(productAttributes)){
								return;
							}
							//创建时间
							productAttribute.setCreateTime(new Date());
							productAttributeService.add(productAttribute,false);
						}else{
							//属性不存在
							throw new BaseServiceException("当前SKU的属性值不存在 name : " + sku.getProductName()+" , id : "+ sku.getProductId());
						}
					}
				});
				//保存对应的价格
				SupplierProductPrice supplierProductPrice = priceCalculation(sku.getHastax(), sku.getTaxCooperatePrice(), sku.getCooperatePrice(), sku.getSalePrice(), sku.getDefaultFreight(), supplierProduct.getId());
				SupplierProductPrice supplierProductPriceQu = new SupplierProductPrice();
				supplierProductPriceQu.setSupplierProductId(supplierProductPrice.getSupplierProductId());
				List<SupplierProductPrice> supplierProductPrices = supplierProductPriceService.queryAll(supplierProductPriceQu);
				if(supplierProductPrices != null && supplierProductPrices.size() > 0){
					return;
				}
				supplierProductPriceService.add(supplierProductPrice,false);
			});
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 /计算价格
	 hastax 是否含税
	 taxCooperatePrice 含税价
	 cooperatePrice 不含税价
	 salePrice 市场价
	 defaultFreight 运费 默认为0
	 */
	public SupplierProductPrice priceCalculation(Integer hastax , Integer taxCooperatePrice , Integer cooperatePrice , Integer salePrice , Integer freight,Long productId){
		//0 不含税 1 含税
		SupplierProductPrice _supplierProductPrice = new SupplierProductPrice();
		//含税价 元
		_supplierProductPrice.setTaxcooperateprice(taxCooperatePrice);
		//不含税价 元
		_supplierProductPrice.setCooperateprice(cooperatePrice);
		//运费
		if (freight == null){
			freight = ProductPrice.DEFAULTSHIPPINGCOST.getName();
		}
		//成本价
		if (0 == hastax){
			_supplierProductPrice.setCostPrice(cooperatePrice + freight);
		}else{
			_supplierProductPrice.setCostPrice(taxCooperatePrice + freight);
		}
		//市场价是否为空
		if(salePrice == null){
			_supplierProductPrice.setSaleprice(_supplierProductPrice.getCostPrice()+ (1*ProductPrice.MARKETPRICEPERCENTAGE.getName()/100));
		}else{
			_supplierProductPrice.setSaleprice(salePrice);
		}
		int private_cost_price = 0;
		if (hastax == 0) {// 不含税
			private_cost_price = _supplierProductPrice.getCooperateprice()+ freight;
		} else {
			private_cost_price = _supplierProductPrice.getTaxcooperateprice() + freight;
		}
		// 求差价
		int diffPrice = _supplierProductPrice.getSaleprice() - private_cost_price;
		if (diffPrice < 0) {
			getLoger().error("严重警告 ,出现负数................................... 产品SKU ID : " + productId);
		}
		int step = diffPrice / 4; // 四个等级，每级的差价
		_supplierProductPrice.setSupplierProductId(Long.valueOf(productId));
		_supplierProductPrice.setMoneyPrice(_supplierProductPrice.getSaleprice());
		_supplierProductPrice.setLeve1Price(private_cost_price + step + step + step);
		_supplierProductPrice.setLeve2Price(private_cost_price + step + step);
		_supplierProductPrice.setLeve3Price(private_cost_price + step);
		_supplierProductPrice.setLeve4Price(private_cost_price);
		_supplierProductPrice.setUnionCostPrice(private_cost_price);
		_supplierProductPrice.setDefaultFreight(freight);
		return _supplierProductPrice;
	}


	public void isProNull(Product pro) throws IllegalAccessException {
		if (StringUtils.isBlank(pro.getName())){
			throw new BaseServiceException("缺少必填参数 : name");
		}
	}

	//封装goods对象
	public SupplierGoods packageObjectGoods(Product pro){
		SupplierGoods supplierGoods = new SupplierGoods();
		//产品名字
		supplierGoods.setName(pro.getName());
		//品牌id
		supplierGoods.setBrandid(Long.valueOf(pro.getBrandid()));
		//品牌中文
		supplierGoods.setBrandnamecn(pro.getBrandnamecn());
		//品牌英文
		supplierGoods.setBrandnameen(pro.getBrandnameen());
		//TODO 一级分类暂时为空
		supplierGoods.setTypeId(null);
		supplierGoods.setTypeName(null);
		//二级分类
		supplierGoods.setCategoryParentId(pro.getCategoryParentId());
		supplierGoods.setCategoryParentName(pro.getCategoryParentName());
		//三级分类
		supplierGoods.setCategoryId(pro.getCategoryId());
		supplierGoods.setCategoryName(pro.getCategoryName());
		//产品详情格式类型 html , pic
		supplierGoods.setGoodsDescType(pro.getGoodsDescType());
		// 这个字段 存储产品介绍详情，如果是图片不从这里取值 ，这里面只存富文本类型
		supplierGoods.setGoodsDesc(pro.getGoodsDesc());
		//供应商系统产品ID，用文本类型为了兼容不同供应商系统
		supplierGoods.setSupplierGoodsId(pro.getSupplierGoodsId());
		//供应商ID
		supplierGoods.setSupplierId(Integer.valueOf(pro.getSupplierId()));
		//供应商名称
		supplierGoods.setSupplierName(pro.getSupplierName());
		//同步时间
		supplierGoods.setCreateTime(new Date());
		//最后更新时间
		supplierGoods.setLastUpdateTime(new Date());
		supplierGoods.setGoodNatureType(pro.getGoodNatureType());
		return supplierGoods;
	}


	public SupplierProduct packageObjectProduct(Sku sku,Long goodsId){
		SupplierProduct supplierProduct = new SupplierProduct();
		supplierProduct.setGid(goodsId);
		//goodsId
		supplierProduct.setGoodsId(sku.getGoodsId());
		//供应商SKU id
		supplierProduct.setProductId(sku.getProductId());
		//供应商SKU name
		supplierProduct.setProductName(sku.getProductName());
		/**
		 * SKU规格图片
		 */
		supplierProduct.setProductImagePath(sku.getProductImagePath());
		/**
		 * 私有云图片地址
		 */
		supplierProduct.setSelfProductImagePath(sku.getSelfProductImagePath());
		/**
		 * SKU 条码
		 */
		supplierProduct.setBarCode(sku.getBarCode());
		/**
		 * 是否含税 0 不含税  1 含税
		 */
		supplierProduct.setHastax(sku.getHastax());
		/**
		 * 供应商产品编码
		 */
		supplierProduct.setGoodsId(sku.getGoodsId());
		/**
		 * 规格字符串JSON格式
		 */
		supplierProduct.setSpecificationsString(sku.getSpecificationsString());
		/**
		 * 0 : 不推送
		 1 : 待推送
		 2 : 已推送
		 3 : 推送失败
		 */
		supplierProduct.setPushStatus(Push.WAIT_PUSH.getName());
		/**
		 * 是否进行图片压缩 0 未压缩 1 已经压缩
		 * */
		supplierProduct.setIsImgCompression(ImageStatus.UNCOMPRESSED.getName());
		/**
		 * 库存数,同步更新
		 */
		supplierProduct.setInventoryNum(sku.getInventoryNum());
		return supplierProduct;
	}
}
